pipeline {
    agent any

    environment {
        // 镜像版本
        IMAGETAG="latest"
        // Harbor私服地址
        HARBOR_URL="192.168.88.131:85"
        // Harbor的项目名称
        HARBOR_PROJECT="demo1"
        PORT=8581
    }


    stages {
        stage('checkout SCM') {
            steps {
                checkout scmGit(branches: [[name: '*/${branch}']], extensions: [], userRemoteConfigs: [[credentialsId: '1', url: 'https://gitee.com/yyyyjinying/free-marker-project.git']])
            }
        }
        stage('Build') {
            steps {
                // 删除镜像
                sh "docker rmi -f ${PROJECTNAME}:${env.IMAGETAG}"
                sh "docker rmi -f ${env.HARBOR_URL}/${env.HARBOR_PROJECT}/${PROJECTNAME}:${env.IMAGETAG}"
                // 本地打包镜像
                sh '/export/server/maven/bin/mvn clean package -Dmaven.test.skip=true dockerfile:build'
                // harbor打标签
                sh "docker tag freemarker-project:latest ${env.HARBOR_URL}/${env.HARBOR_PROJECT}/${PROJECTNAME}:${env.IMAGETAG}"
                withCredentials([usernamePassword(credentialsId: 'da43e271-0a0d-44cd-8987-f9fbabee57a0', passwordVariable: 'password', usernameVariable: 'username')]) {
                    // 登录
                    sh "docker login -u ${username} -p ${password} ${env.HARBOR_URL}"
                    // 上传
                    sh "docker push ${env.HARBOR_URL}/${env.HARBOR_PROJECT}/${PROJECTNAME}:${env.IMAGETAG}"
                    // 删除本地镜像
                    sh "docker rmi -f ${PROJECTNAME}:${env.IMAGETAG}"
                    sh "docker rmi -f ${env.HARBOR_URL}/${env.HARBOR_PROJECT}/${PROJECTNAME}:${env.IMAGETAG}"
                }
            }
        }
        stage('Deploy') {
            steps {

                script {
                    def remote = [:]
                    remote.name = 'node1'
                    remote.host = '192.168.88.131'
                    remote.allowAnyHosts = true
                    withCredentials([sshUserPrivateKey(credentialsId: '12', keyFileVariable: 'identity', passphraseVariable: 'sh123456', usernameVariable: 'userName')]) {
                        remote.user = userName
                        remote.identityFile = identity

                        // 执行远程脚本jar-start.sh，传递一个参数arg1 PORT实际暴漏的端口号可以自由设置
                        def commandWithArgs = "/export/server/docker-start/base/sores/jenkins/execssh/image_deploy.sh ${env.HARBOR_URL} ${env.HARBOR_PROJECT} ${PROJECTNAME} ${env.IMAGETAG} ${env.PORT}"
                        sshCommand remote: remote, command: commandWithArgs
                    }
                }

                 echo 'build project success ${ANOTHER_VAR}'
            }
        }
    }
}
